package com.zym.init.auth.service;

import com.zym.init.constant.CommonConstant;
import com.zym.init.model.bo.LoginUser;
import com.zym.init.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * 自定义权限实现，ss取自SpringSecurity首字母
 */
@Service("ss")
public class PermissionAnnotation {

    /**
     * 判断用户是否拥有某个角色
     *
     * @param role 角色字符串
     * @return 用户是否具备某角色
     */
    public boolean hasRole(String role) {
        if (!StringUtils.hasLength(role)) {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUserPo().getRoleList())) {
            return false;
        }
        for (String roleKey : loginUser.getUserPo().getRoleList()) {
            if (CommonConstant.SUPER_ADMIN.equals(roleKey) || roleKey.equals(role)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断用户是否拥有某个权限
     */
    public boolean hasPermission(String permission) {
        if (!StringUtils.hasLength(permission))
        {
            return false;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissionList()))
        {
            return false;
        }
        for (String permissionKey : loginUser.getPermissionList()) {
            if (CommonConstant.ALL_PERMISSION.equals(permissionKey) || permissionKey.equals(permission)) {
                return true;
            }
        }
        return false;
    }

}
